home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3391 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  2.2 KB

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: [] overload..(newbie in distress)
  5. Date: 23 Jan 1996 20:15:59 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan23151559@g7240065.bridge.bst.bls.com>
  8. References: <DLGppJ.31C@undergrad.math.uwaterloo.ca>
  9.     <Robert.Lendvai-2101960118330001@129.170.80.94>
  10.     <4dtuam$hf4@news.xmission.com>
  11.     <ALUN.CHAMPION.96Jan22143422@g7240065.bridge.bst.bls.com>
  12.     <4e12is$5no@engnews1.Eng.Sun.COM>
  13. NNTP-Posting-Host: bstfirewall.bst.bls.com
  14. In-reply-to: RAJU ALLURI's message of 22 Jan 1996 22:20:12 GMT
  15.  
  16. In article <4e12is$5no@engnews1.Eng.Sun.COM> RAJU ALLURI <raju.alluri@Sun.COM> writes:
  17.  
  18. : Alun.Champion@bridge.bst.bls.com (Alun Champion) wrote:
  19. [snip]
  20. :> And if it is necessary what is the argument against
  21. :>
  22. *>   const T& operator [] (int index) const;      (3)
  23. :>
  24. *> instead of
  25. :>
  26. *>   T operator [] (int index) const;       (2)
  27.  
  28. [snip]
  29. : Then let us come to the third member function:
  30. :    const T& operator [] (int index) const;
  31. : Remember, it returns a reference (even though it is a constant)
  32. : Most of the compilers allow you to EXPLICITLY type convert a constant 
  33. : reference to an non-constant one, and if it is done, the constness 
  34. : of the object is lost.
  35. : Hence the second construct is a better one than the third construct.
  36.  
  37. [snip]
  38.  
  39. : void foo( Array a, const Array ca )
  40. : {
  41.        a[2] = 100;    // Fine! calls first one!
  42.        a[3] = ca[3]    // Fine! calls first one on a and second one on ca!
  43.        ca[2] = 200;    // Error! return value of second [] operator is not an
  44.                //        lvalue!
  45. : }
  46.  
  47. : Instead, if you use the third type of function for the constant objects,
  48. : then some wicked fellow like me can do like
  49.        (int &)(ca[2]) = 200;
  50. : and make the constant object changed!
  51.  
  52. This doesn't really hold much weight as some wicked fellow like me can
  53. circumvent the constness of the ARRAY anyway like:
  54.  
  55.            ((Array&)ca)[2] = 200;
  56.  
  57. The third option prevents any unnecessary copying, which for large T
  58. or complex T with deep copy semantics can be a significant saving.
  59.  
  60. Regards
  61.  
  62.    -A.
  63.  
  64. NB [*> - means slightly changed from original post]
  65. -- 
  66. | A.Champion                |
  67.